package com.qdc.datacenters.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.anji.captcha.util.MD5Util;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qdc.datacenters.domain.entity.BaseEntity;
import com.qdc.datacenters.domain.entity.ChatContactMsg;
import com.qdc.datacenters.domain.entity.ChatContactMsgAttachment;
import com.qdc.datacenters.domain.query.chatmsg.ChatMsgListQuery;
import com.qdc.datacenters.domain.query.chatmsg.ChatMsgQuery;
import com.qdc.datacenters.domain.vo.chatmsg.*;
import com.qdc.datacenters.enums.DeleteStatusEnum;
import com.qdc.datacenters.mapper.ChatContactMsgMapper;
import com.qdc.datacenters.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 会话消息(ChatContactMsg)表服务实现类
 *
 * @author danmo
 * @since 2024-02-28 17:24:23
 */
@Service
public class ChatContactMsgServiceImpl extends BaseServiceImpl<ChatContactMsgMapper, ChatContactMsg> implements IChatContactMsgService {

    @Autowired
    private ICorpCustomerService iCorpCustomerService;

    @Autowired
    private ICorpGroupService iCorpGroupService;

    @Autowired
    private ICorpPermitUserService iCorpPermitUserService;

    @Autowired
    private IChatContactMsgAttachmentService iChatContactMsgAttachmentService;


    public List<ChatMsgUserListVo> getUserMsgList(ChatMsgListQuery query){
        return this.iCorpPermitUserService.getUserMsgList(query);
    }

    public List<ChatMsgCustomerListVo> getCustomerMsgList(ChatMsgListQuery query){
        return this.iCorpCustomerService.getCustomerMsgList(query);
    }

    public List<ChatMsgRoomListVo> getRoomMsgList(ChatMsgListQuery query){
        return this.iCorpGroupService.getRoomMsgList(query);
    }

    public List<ChatMsgExCustomerVo> getExternalCustomerList(ChatMsgListQuery query){
        return this.baseMapper.getExternalCustomerList(query);
    }

    public List<ChatMsgInCustomerVo> getInternalCustomerList(ChatMsgListQuery query){
        return this.baseMapper.getInternalCustomerList(query);
    }
    public List<ChatMsgGroupVo> getExternalGroupList(ChatMsgListQuery query){
        return this.baseMapper.getExternalGroupList(query);
    }
    public List<ChatMsgGroupVo> getInternalGroupList(ChatMsgListQuery query){
        return this.baseMapper.getInternalGroupList(query);
    }

    public List<ChatMsgCustomerUserVo> getCustomerUserList(ChatMsgListQuery query){
        return this.baseMapper.getCustomerUserList(query);
    }

    public List<ChatContactMsgVo> getChatMsgList(ChatMsgQuery query){
        if(StringUtils.isNotEmpty(query.getUserId()) || StringUtils.isNotEmpty(query.getCustomerId())){
            String roomStr = String.join("", ListUtil.toList(query.getUserId(), query.getCustomerId()).stream().sorted().toList());
            query.setRoomId(MD5Util.md5(roomStr));
        }
        //当使用ID查询时，计算所在页数
        if(Objects.nonNull(query.getId())){
            Long count = count(new LambdaQueryWrapper<ChatContactMsg>()
                    .eq(ChatContactMsg::getRoomId, query.getRoomId())
                    .lt(ChatContactMsg::getId, query.getId())
                    .orderByAsc(ChatContactMsg::getMsgTime));
            int pageNum = count.intValue()/query.getPageSize() + 1;
            query.setPageIndex(pageNum);
        }
        startPage(query.getPageIndex(), query.getPageSize(),query.getSortField(),query.getSort());
        List<ChatContactMsgVo> chatMsgList = this.baseMapper.getChatMsgList(query);
        if(CollectionUtil.isNotEmpty(chatMsgList)){
            List<Long> msgIds = chatMsgList.stream().map(ChatContactMsgVo::getId).toList();
            List<ChatContactMsgAttachment> attachmentList = iChatContactMsgAttachmentService.list(new LambdaQueryWrapper<ChatContactMsgAttachment>()
                    .in(ChatContactMsgAttachment::getMsgId, msgIds).eq(BaseEntity::getDelFlag, DeleteStatusEnum.DELETE_NO.getIndex()));
            if(CollectionUtil.isNotEmpty(attachmentList)){
                Map<Long, List<ChatMsgAttachmentVo>> listMap = attachmentList.stream().map(item -> {
                    ChatMsgAttachmentVo msgAttachmentVo = new ChatMsgAttachmentVo();
                    BeanUtils.copyProperties(item,msgAttachmentVo);
                    return msgAttachmentVo;
                }).collect(Collectors.groupingBy(ChatMsgAttachmentVo::getMsgId));
                for (ChatContactMsgVo contactMsgVo : chatMsgList) {
                    contactMsgVo.setAttachment(listMap.get(contactMsgVo.getId()));
                }
            }
        }
        return chatMsgList;
    }


    @Override
    public ChatContactMsgAttachment getAttachmentByMd5(String md5) {
        return iChatContactMsgAttachmentService.getOne(new LambdaQueryWrapper<ChatContactMsgAttachment>()
                .eq(ChatContactMsgAttachment::getMd5,md5)
                .eq(ChatContactMsgAttachment::getDelFlag, DeleteStatusEnum.DELETE_NO.getIndex())
                .last("limit 1"));
    }

    @Override
    public void saveAttachment(ChatContactMsgAttachment msgAttachment) {
        iChatContactMsgAttachmentService.save(msgAttachment);
    }
}

